package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.budwk.app.jim.SqfwWebSocket;
import com.budwk.app.jim.WebSocketMsgDTO;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.dto.TransferServiceRecordDTO;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.models.Sqfw_workorder;
import com.budwk.app.sqfw.services.SqfwServicerecordService;
import com.budwk.app.sqfw.services.SqfwWorkorderService;
import com.budwk.app.sqfw.vo.PopoFriendWorkOrderVO;
import com.budwk.app.sqfw.vo.SqfwWorkOrderVO;
import com.budwk.app.sqfw.vo.TransferMessageVO;
import com.budwk.app.sys.models.Sys_dict;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.util.WordTest;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@IocBean
@At("/platform/sqfw/workorder")
@ApiDefinition(tag = "工单服务")
@Slf4j
public class SqfwWorkorderController {

    @Inject
    Dao dao;

    @Inject
    private SqfwWorkorderService sqfwWorkorderService;

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SysUnitService sysUnitService;

    @Inject
    private SysDictService sysDictService;

    @Inject
    private SqfwWebSocket sqfwWebSocket;

    @Inject
    private PropertiesProxy propertiesProxy;

    @Inject
    private SysOssService sysOssService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询工单服务")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_workorder.class
    )
    @ApiResponses(
            implementation = Sqfw_workorder.class
    )
    @SaCheckLogin
    public Result<?> list(@Param("..") Sqfw_workorder bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize,
                          @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy,
                          @Param("delflag") Boolean delflag) {
        Cnd cnd = Cnd.NEW();

        if (bean == null) return Result.data(sqfwWorkorderService.listPage(pageNo, pageSize, cnd));

        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("createdat", "desc");
        }

        if (bean.getSqfw_id() != null && Strings.isNotBlank(bean.getSqfw_id().toString())) {
            cnd.and("sqfw_id", "=", bean.getSqfw_id());
        }

        if (bean.getUser_name() != null && Strings.isNotBlank(bean.getUser_name().toString())) {
            cnd.and("user_name", "=", bean.getUser_name());
        }

        if (bean.getWk_status() != null && Strings.isNotBlank(bean.getWk_status().toString())) {
            cnd.and("wk_status", "=", bean.getWk_status());
        }

        if (bean.getWk_grade() != null && Strings.isNotBlank(bean.getWk_grade().toString())) {
            cnd.and("wk_grade", "=", bean.getWk_grade());
        }

        if (bean.getWk_priority() != null && Strings.isNotBlank(bean.getWk_priority().toString())) {
            cnd.and("wk_priority", "=", bean.getWk_priority());
        }

        if (bean.getComplete_time() != null && Strings.isNotBlank(bean.getComplete_time().toString())) {
            cnd.and("complete_time", "=", bean.getComplete_time());
        }

        if (bean.getRemark() != null && Strings.isNotBlank(bean.getRemark().toString())) {
            cnd.and("remark", "=", bean.getRemark());
        }

        if (StringUtils.isNotBlank(bean.getFromUserId())) {
            cnd.and("from_user_id", "=", bean.getFromUserId());
        }

        if (StringUtils.isNotBlank(bean.getToUserId())) {
            cnd.and("to_user_id", "=", bean.getToUserId());
        }

        if (StringUtils.isNotBlank(bean.getUser_id())) {
            cnd.and("user_id", "=", bean.getUser_id());
        }

        if (StringUtils.isNotBlank(bean.getServiceType())) {
            cnd.and("service_type", "=", bean.getServiceType());
        }

        if (delflag != null) cnd.and("delflag", "=", delflag);

        Pagination pagination = sqfwWorkorderService.listPage(pageNo, pageSize, cnd);
        List<Sqfw_workorder> list = pagination.getList(Sqfw_workorder.class);

        List<SqfwWorkOrderVO> resultList = sqfwWorkorderService.getVO(list);
        pagination.setList(resultList);

        return Result.data(pagination);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增工单服务")
    @ApiFormParams(
            implementation = Sqfw_workorder.class
    )
    @ApiResponses
    @SLog(tag = "新增工单服务", value = "${args[0].id}")
    @SaCheckPermission("sqfw.workorder.create")
    public Result<?> create(@Param("..") Sqfw_workorder sqfwServicerecord, HttpServletRequest req) {
        sqfwServicerecord.setCreatedBy(SecurityUtil.getUserId());
        sqfwServicerecord.setCreateDate(new Date());
        sqfwServicerecord.setUpdatedBy(SecurityUtil.getUserId());
        sqfwServicerecord.setUpdatedAt(new Date());
        sqfwWorkorderService.insert(sqfwServicerecord);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改工单服务")
    @ApiFormParams(
            implementation = Sqfw_workorder.class
    )
    @ApiResponses
    @SLog(tag = "修改工单服务", value = "${args[0].id}")
    @SaCheckLogin
    public Result<?> update(@Param("..") Sqfw_workorder sqfwWorkorder, HttpServletRequest req) {
        sqfwWorkorder.setUpdatedBy(SecurityUtil.getUserId());
        sqfwWorkorder.setUpdatedAt(new Date());

        String existWorkOrderId = sqfwWorkorder.getId();
        Sqfw_workorder existWorkOrder = sqfwWorkorderService.fetch(existWorkOrderId);
        if (StringUtils.isNotBlank(sqfwWorkorder.getWk_status())
                && !sqfwWorkorder.getWk_status().equals(existWorkOrder.getWk_status())  // 如果修改的工单状态是完成，并且是第一次完成，则赋值完成时间
                && sqfwWorkorder.getWk_status().equals("complete")) {

            if (existWorkOrder.getUser_id().equals(existWorkOrder.getCreatedBy())) {
                // 说明是自己上传的工单 需要查看已经转发的工单是否已经完成了
                // 如果已经转发的工单还没有全部完成那么不能进行修改
                List<Sqfw_workorder> otherCompleteWorkOrderList = sqfwWorkorderService
                        .query(Cnd.where("sqfw_id", "=", existWorkOrder.getSqfw_id())
                                .and("user_id", "!=", existWorkOrder.getUser_id())
                                .and("wk_status", "!=", "complete")
                                .and("delflag", "=", false));
                if (otherCompleteWorkOrderList.size() > 0) return Result.error("已转发工单尚全部完成,暂时不能操作!");
            }

            sqfwWorkorder.setComplete_time(new Date());
        }
        sqfwWorkorderService.updateIgnoreNull(sqfwWorkorder);

        // wzy 2023-5-22 如果是修改了工单的优先级 则相应的服务记录对应的工单状态都需要改变 只有等级为1的才能进行这个操作
        if (StringUtils.isNotBlank(sqfwWorkorder.getWk_priority())
                && existWorkOrder.getWk_grade().equals("0")) {
            sqfwWorkorderService.update(Chain.make("wk_priority", sqfwWorkorder.getWk_priority()), Cnd.where("sqfw_id", "=", existWorkOrder.getSqfw_id()));
        }
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取工单服务")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckLogin
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        Sqfw_workorder sqfwServicerecord = sqfwWorkorderService.fetch(id);
        if (sqfwServicerecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(sqfwServicerecord);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除工单服务")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除工单服务", value = "${args[0]}")
    @SaCheckPermission("sqfw.workorder.delete")
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_workorder sqfwServicerecord = sqfwWorkorderService.fetch(id);
        if (sqfwServicerecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwWorkorderService.delete(id);
        req.setAttribute("_slog_msg", sqfwServicerecord.getId());
        return Result.success();
    }

    /**
     * 将word中某些标签替换成指定的值，并生成一个新的word文档。
     *
     * @throws IOException
     */

    @At("/getCallNumber")
    @Ok("json")
    @POST
    @ApiOperation(name = "word插入数据")
    @ApiFormParams()
    @SLog(tag = "word插入数据", value = "${args[0]},${args[1]},${args[2]}")
    //@SaCheckPermission("sqfw.servicerecord.getCallNumber")
    public Result getCallNumber(@Param("type") String type, @Param("startTime") String startTime, @Param("endTime") String endTime) throws ParseException {
        Result result = Result.NEW();
        Map map = new HashMap();

        Timestamp starttimestamp = Timestamp.valueOf(startTime);
        Timestamp endtimestamp = Timestamp.valueOf(endTime);
        //查询工单今日通话数量
        Cnd connectNumCnd = Cnd.NEW();
        connectNumCnd.and("user_name", "=", SecurityUtil.getUserUsername());
        connectNumCnd.and("createdat", ">=", starttimestamp);
        connectNumCnd.and("createdat", "<=", endtimestamp);
        connectNumCnd.and("delflag", "=", false);
        List<Sqfw_workorder> connectNum = sqfwWorkorderService.query(connectNumCnd);

        List<String> listUnit = sqfwServicerecordService.listAllServiceOrderType(SecurityUtil.getUnitId());

        //查询服务记录今日通话数量

        Cnd serviceconnectNumCnd = Cnd.NEW();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Long beginUseTime = sdf.parse(startTime).getTime();
        Long endUseTime = sdf.parse(endTime).getTime();
        serviceconnectNumCnd.and("customer_name", "=", SecurityUtil.getUserUsername());
        serviceconnectNumCnd.and("createdat", ">=", beginUseTime);
        serviceconnectNumCnd.and("createdat", "<=", endUseTime);
        List<Sqfw_servicerecord> serviceconnectNum = sqfwServicerecordService.query(serviceconnectNumCnd);

        //查询工单今日完成条数
        DecimalFormat df = new DecimalFormat("0.00");

        Cnd finishNumCnd = Cnd.NEW();
        finishNumCnd.and("user_name", "=", SecurityUtil.getUserUsername());
        finishNumCnd.and("wk_status", "=", "complete");
        finishNumCnd.and("complete_time", ">=", starttimestamp);
        finishNumCnd.and("complete_time", "<=", endtimestamp);
        connectNumCnd.and("delflag", "=", false);

        List<Sqfw_workorder> finishNum = sqfwWorkorderService.query(finishNumCnd);


        //查询服务记录工单今日完成条数
        Cnd servicefinishNumCnd = Cnd.NEW();
        servicefinishNumCnd.and("customer_name", "=", SecurityUtil.getUserUsername());
        servicefinishNumCnd.and("finish_status", "=", "complete");
        servicefinishNumCnd.and("createdat", ">=", beginUseTime);
        servicefinishNumCnd.and("createdat", "<=", endUseTime);
        List<Sqfw_servicerecord> servicefinishNum = sqfwServicerecordService.query(servicefinishNumCnd);

       /* int allanquan=0;
        int allguanli=0;
        int alldangjian=0;
        int allfuwu=0;

        for (int i=0;i<serviceconnectNum.size();i++){
            if (serviceconnectNum.get(i).getType().contains("安全")){
                allanquan++;
            }
            if (serviceconnectNum.get(i).getType().contains("党建")){
                alldangjian++;
            }
            if (serviceconnectNum.get(i).getType().contains("服务")){
                allfuwu++;
            }
            if (serviceconnectNum.get(i).getType().contains("管理")){
                allguanli++;
            }
        }
        int allqita=serviceconnectNum.size()-allanquan-alldangjian-allfuwu-allguanli;
        int finishanquan=0;
        int finishguanli=0;
        int finishdangjian=0;
        int finishfuwu=0;
        for (int i=0;i<servicefinishNum.size();i++){
            if (servicefinishNum.get(i).getType().contains("安全")){
                finishanquan++;
            }
            if (servicefinishNum.get(i).getType().contains("党建")){
                finishdangjian++;
            }
            if (servicefinishNum.get(i).getType().contains("服务")){
                finishfuwu++;
            }
            if (servicefinishNum.get(i).getType().contains("管理")){
                finishguanli++;
            }
        }
        int finishqita=servicefinishNum.size()-finishanquan-finishdangjian-finishfuwu-finishguanli;
*/

        String sqlsall = " SELECT  user_name,type,count(1) from (SELECT * from (select tb.*,ta.type,ta. connect_time from  shequ.sqfw_servicerecord ta left join shequ.sqfw_workorder tb on ta.id=tb.sqfw_id) tt where createdat>='" + starttimestamp + "' and createdat<='" + endtimestamp + "'  and  delflag=false   and user_name='" + SecurityUtil.getUserUsername() + "') tc GROUP BY type ,user_name";
        //String sqlsfinish = " SELECT * from (select tb.*,ta.type  from  shequ.sqfw_servicerecord ta left join shequ.sqfw_workorder tb on ta.id=tb.sqfw_id) tt where complete_time>='" + starttimestamp + "' and complete_time<='" + endtimestamp + "' and user_name='" + SecurityUtil.getUserUsername() + "' and wk_status='complete' and delflag=false";
        Sql sqlall = Sqls.create(sqlsall);


        sqlall.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                List listall = new LinkedList();

                while (rs.next()) {
                    HashMap c = new HashMap();
                    if (StringUtils.isNotBlank(rs.getString("type"))) {
                        c.put("typeall", rs.getString("type"));
                        c.put("countall", rs.getString("count"));
                        listall.add(c);
                    }

                }
                return listall;
            }
        });//实体回调，不构建实体类

        dao.execute(sqlall);
        List<HashMap> listall = sqlall.getList(HashMap.class);
           /* Entity<Record> entity1 = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
            sqlfinish.setEntity(entity1);
            dao.execute(sqlfinish);*/


        String sqlsfinish = " SELECT  user_name,type,count(1) from (SELECT * from (select tb.*,ta.type,ta. connect_time from  shequ.sqfw_servicerecord ta left join shequ.sqfw_workorder tb on ta.id=tb.sqfw_id) tt where complete_time>='" + starttimestamp + "' and complete_time<='" + endtimestamp + "'  and  delflag=false and wk_status='complete'  and user_name='" + SecurityUtil.getUserUsername() + "') tc GROUP BY type ,user_name";
        //String sqlsfinish = " SELECT * from (select tb.*,ta.type  from  shequ.sqfw_servicerecord ta left join shequ.sqfw_workorder tb on ta.id=tb.sqfw_id) tt where complete_time>='" + starttimestamp + "' and complete_time<='" + endtimestamp + "' and user_name='" + SecurityUtil.getUserUsername() + "' and wk_status='complete' and delflag=false";
        Sql sqlfinish = Sqls.create(sqlsfinish);


        sqlfinish.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                List listfinish = new LinkedList();

                while (rs.next()) {
                    HashMap c = new HashMap();
                    if (StringUtils.isNotBlank(rs.getString("type"))) {
                        c.put("typefinish", rs.getString("type"));
                        c.put("countfinish", rs.getString("count"));
                        listfinish.add(c);
                    }

                }
                return listfinish;
            }
        });//实体回调，不构建实体类

        dao.execute(sqlfinish);
        List<HashMap> listfinish = sqlfinish.getList(HashMap.class);


        Sys_unit sys_unit = sysUnitService.fetch(SecurityUtil.getUnitId());

        Cnd cnd = Cnd.NEW();
        if (!Strings.isNotBlank(sys_unit.getParentId())) {
            cnd.and("unitid", "=", SecurityUtil.getUnitId());
        } else {
            cnd.and("unitid", "=", sys_unit.getParentId());
        }
        Sys_dict sys_dict = sysDictService.fetch(cnd);

        Cnd cnd1 = Cnd.NEW();

        cnd1.and("parentid", "=", sys_dict.getId());

        Map<String, Integer> allMap = Maps.newHashMap();
        for (HashMap allWorkMap : listall) {
            String typeAll = (String) allWorkMap.get("typeall");
            String countAllStr = (String) allWorkMap.get("countall");
            Integer countAll = Integer.parseInt(countAllStr);

            allMap.put(typeAll, countAll);
        }

        // 完成的和上面一样
        Map<String, Integer> finishMap = Maps.newHashMap();
        for (HashMap finishWorkMap : listfinish) {
            String typeAll = (String) finishWorkMap.get("typefinish");
            String countAllStr = (String) finishWorkMap.get("countfinish");
            Integer countAll = Integer.parseInt(countAllStr);
            finishMap.put(typeAll, countAll);
        }


       /* map.put("allanquan",allanquan);
        map.put("allguanli",allguanli);
        map.put("alldangjian",alldangjian);
        map.put("allfuwu",allfuwu);
        map.put("allqita",allqita);
        map.put("finishanquan",finishanquan);
        map.put("finishguanli",finishguanli);
        map.put("finishdangjian",finishdangjian);
        map.put("finishfuwu",finishfuwu);
        map.put("finishqita",finishqita);*/


        List<Map> list = new ArrayList<>();
        list.add(allMap);
        list.add(finishMap);

        result.addData(list);
        //result.addData(finishMap);

        return result;
    }


    /**
     * 将word中某些标签替换成指定的值，并生成一个新的word文档。
     *
     * @throws IOException
     */

    @At("/insertAndOutFile")
    @Ok("json")
    @POST
    @ApiOperation(name = "word插入数据")
    @ApiFormParams()
    @SLog(tag = "word插入数据", value = "${args[0]}")
    //@SaCheckPermission("sqfw.servicerecord.insertAndOutFile")
    public Result insertAndOutFile2(@Param("type") String type, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("list") List<Map> list) throws ParseException {
        Result result = Result.NEW();
        Map<String, String> map = new HashMap<>();
        Map resultmap = new HashMap();
        String pdf = "";
        String templateFile = propertiesProxy.get("cusconfig.report.reportPath") + "/file/金元小助播报模板.docx";
        //String templateFile = "C:\\Users\\CXB-WGW\\Desktop\\file\\金元小助播报模板.docx";

        Sys_unit sys_unit = sysUnitService.fetch(SecurityUtil.getUnitId());

        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat1.parse(startTime);
        Calendar calendar = Calendar.getInstance();
        //设置星期一为一周开始的第一天
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        //设置在一年中第一个星期所需最少天数
        calendar.setMinimalDaysInFirstWeek(0);
        calendar.setTime(parse);
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        System.out.println(week);
        if (week == 1 && parse.getMonth() == 11) {
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 7);
            Date pastDate = calendar.getTime();
            String result1 = simpleDateFormat1.format(pastDate);
            System.out.println(result1);
            week = calendar.get(Calendar.WEEK_OF_YEAR) + 1;
            System.out.println(week);
        }


        String timestr = startTime.substring(0, 4) + "年" + startTime.substring(5, 7) + "月" + startTime.substring(8, 10) + "日";


        //String timestr1=startTime.substring(0,4)+"年"+startTime.substring(5,7)+"月"+startTime.substring(8,10)+"日"+" "+startTime.substring(11,16);

        SimpleDateFormat simpleDateFormatnow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowdate = simpleDateFormatnow.format(new Date());
        map.put("data", nowdate.substring(0, 4) + "年" + nowdate.substring(5, 7) + "月" + nowdate.substring(8, 10) + "日" + " " + nowdate.substring(11, 16));
        map.put("unit", sys_unit.getName());

        String uploadresult = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = simpleDateFormat.format(new Date());
        if (type.equals("日报")) {
            map.put("type", type);
            map.put("time", timestr);
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
            //pdf = "C:\\Users\\CXB-WGW\\Desktop\\file\\pdf\\" + date + file.getName().replace("模板.docx", "") + type + ".pdf";

        }

        if (type.equals("周报")) {
            map.put("type", type);
            map.put("time", startTime.substring(0, 4) + "年第" + week + "周" + "(" + startTime.substring(6, 7) + "/" + startTime.substring(8, 10) + "—" + endTime.substring(6, 7) + "/" + endTime.substring(8, 10) + ")");
            map.put("今日", "本周");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
            //pdf = "C:\\Users\\CXB-WGW\\Desktop\\file\\pdf\\" + date + file.getName().replace("模板.docx", "") + type + ".pdf";

        }

        if (type.equals("月报")) {
            map.put("type", type);
            map.put("time", startTime.substring(0, 4) + "年" + startTime.substring(5, 7) + "月");
            map.put("今日", "本月");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
            //pdf = "C:\\Users\\CXB-WGW\\Desktop\\file\\pdf\\" + date + file.getName().replace("模板.docx", "") + type + ".pdf";

        }

        if (type.equals("")) {
            map.put("type", type);
            map.put("time", startTime.substring(0, 4) + "年" + startTime.substring(5, 7) + "月" + startTime.substring(8, 10) + "日" + "—" + endTime.substring(0, 4) + "年" + endTime.substring(5, 7) + "月" + endTime.substring(8, 10) + "日");
            map.put("今日", "");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
            //pdf = "C:\\Users\\CXB-WGW\\Desktop\\file\\pdf\\" + date + file.getName().replace("模板.docx", "") + type + ".pdf";

        }
        // 模板文件
        String filename = UUID.randomUUID().toString();
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/word/" + filename + ".docx";
        //String outPath = "C:\\Users\\CXB-WGW\\Desktop\\file\\word\\" + filename + ".docx";
        try {
            String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/金元小助播报模板.docx";
            //String templateFilePath = "C:\\Users\\CXB-WGW\\Desktop\\file\\金元小助播报模板.docx";

            InputStream is1 = new FileInputStream(templateFilePath);
            InputStream is2 = new FileInputStream(templateFilePath);
            // 用来替换变量
            XWPFDocument hdt = new XWPFDocument(is1);
            // 用来输出原格式
            XWPFDocument hdt1 = new XWPFDocument(is2);

            Timestamp starttimestamp = Timestamp.valueOf(startTime);
            Timestamp endtimestamp = Timestamp.valueOf(endTime);

            map.put("name", SecurityUtil.getUserUsername());

            for (Map listMap : list) {
                if (listMap.get("name").equals("总任务")) {
                    map.put("callnumber", listMap.get("all").toString());
                    map.put("finishnumber", listMap.get("finish").toString());
                }

            }

            //查询工单今日完成条数
            DecimalFormat df = new DecimalFormat("0.00");
            StringBuilder resultContentSB = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).get("name").equals("总任务")) {
                    continue;
                }
                String resultStr = list.get(i).get("name") + "类" + list.get(i).get("all") + "条，完结" + list.get(i).get("finish") + "条";
                resultStr = "\t" + resultStr + "\n\n";
                resultContentSB.append(resultStr);
            }

            //插入主体值
            map.put("dataset", resultContentSB.toString());

            File outFilePath = new File(outPath);
            try {
                // 生成新的文件并写到硬盘
                XWPFTemplate.compile(templateFilePath).render(map, new FileOutputStream(outFilePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            hdt.close();
            hdt1.close();

            WordTest.wordToPdf(outPath, pdf);
            SysOss upload = sysOssService.upload(FileUtil.file(pdf));
            if (upload != null) uploadresult = upload.getUrl();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.data(uploadresult);
    }

    /**
     * 替换文档中的参数（word）
     *
     * @param doc
     * @param params
     */

    private static void replaceText(XWPFDocument doc, Map<String, String> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            replaceInPara(para, params);
        }
    }


    /**
     * 替换段落中的参数（word）
     *
     * @param para
     * @param params
     */

    private static void replaceInPara(XWPFParagraph para, Map<String, String> params) {
        List<XWPFRun> runs = para.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.toString();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (runText.contains(entry.getKey())) {
                    para.removeRun(i);
                    // 重新插入run里内容格式可能与原来模板的格式不一致
                    para.insertNewRun(i).setText(runText.replace(entry.getKey(), entry.getValue()));
                }
            }
        }
    }



    /**
     * 处理段落替换内容的格式问题（word）
     *
     * @param
     * @param
     */

    private static void setStyleInPara(XWPFParagraph para, XWPFParagraph para2) {
        List<XWPFRun> runs = para.getRuns();
        List<XWPFRun> runs2 = para2.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            XWPFRun run2 = runs2.get(i);
            run2.getCTR().setRPr(run.getCTR().getRPr());
        }
    }


    @At("/transferServiceRecordOld")
    @Ok("json")
    @POST
    @ApiOperation(name = "转发消息")
    @ApiFormParams(
            implementation = Sqfw_workorder.class
    )
    @SLog(tag = "转发信息", value = "${args[0]}")
    public Result<?> transferServiceRecordOld(@Param("..") TransferServiceRecordDTO dto) {
        if (StringUtils.isBlank(dto.getServiceRecordId())) return Result.error("服务记录id不能为空");
        TransferMessageVO transferCount = sqfwWorkorderService.transferServiceRecord(dto);
        if (transferCount.getSuccessSendCount() >= 0) return Result.success(transferCount);

        return Result.error("消息未成功发送!");
    }

    @At("/transferServiceRecord")
    @Ok("json")
    @POST
    @ApiOperation(name = "转发消息")
    @ApiFormParams(
            implementation = Sqfw_workorder.class
    )
    @SLog(tag = "转发信息", value = "${args[0]}")
    public Result<?> transferServiceRecordNew(@Param("..") TransferServiceRecordDTO dto) {
        if (StringUtils.isBlank(dto.getServiceRecordId())) return Result.error("服务记录id不能为空");
        TransferMessageVO transferCount = sqfwWorkorderService.transferServiceRecordNew(dto);
        if (transferCount.getSuccessSendCount() >= 0) return Result.success(transferCount);

        return Result.error("消息未成功发送!");
    }

    @At("/updateWorkOrderWkStatus")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据一些信息修改工单状态")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "sqfwId", example = "1", description = "服务单id", type = "integer"),
                    @ApiFormParam(name = "userId", example = "10", description = "用户id", type = "integer"),
                    @ApiFormParam(name = "wkStatus", example = "createdAt", description = "工单状态"),
                    @ApiFormParam(name = "remark", example = "descending", description = "备注")
            },
            implementation = Sqfw_workorder.class
    )
    public Result<?> updateWorkOrderWkStatus(@Param("sqfwId") String sqfwId,
                                             @Param("userId") String userId,
                                             @Param("wkStatus") String wkStatus,
                                             @Param("remark") String remark) {
        if (StringUtils.isBlank(sqfwId)) Result.error("缺少参数sqfwId");
        if (StringUtils.isBlank(userId)) Result.error("缺少参数userId");
        if (StringUtils.isBlank(wkStatus)) Result.error("缺少参数wkStatus");

        // 其实这个只是会修改一条工单的状态
        Sqfw_workorder workOrder = sqfwWorkorderService.fetch(Cnd.where("sqfw_id", "=", sqfwId).and("user_id", "=", userId).and("delflag", "=", false));
        if (workOrder == null) return Result.error("工单不存在!请检查服务记录id和人员id");

        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);

        // 只有没有删除的才能更改
        int deleteSize = 0;
        if (wkStatus.equals("complete") && !workOrder.getWk_status().equals(wkStatus)) {
            // 如果已经完成了则会给创建服务记录的人发送一个消息
            if (serviceRecord != null) {
                Map<String, Object> paramMap = Maps.newHashMap();
                paramMap.put(SqfwWebSocketMsgConstants.service_record_id, sqfwId);
                paramMap.put(SqfwWebSocketMsgConstants.work_order_id, workOrder.getSqfw_id());

                WebSocketMsgDTO msg = new WebSocketMsgDTO(SqfwWebSocketMsgConstants.work_flow_finished, "工作流已经完成");
                msg.setRelatedParams(paramMap);
                sqfwWebSocket.sendMessage(serviceRecord.getCreatedBy(), msg);
            }
            workOrder.setComplete_time(new Date());
        }

        workOrder.setWk_status(wkStatus);
        workOrder.setRemark(remark);
        sqfwWorkorderService.updateIgnoreNull(workOrder);
        deleteSize++;

        return Result.success(deleteSize);
    }



    @At("/getPopoFriendWorkOrderList")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据泡泡用户id获取工单情况")
    public Result<List<PopoFriendWorkOrderVO>> getPopoFriendNotCompleteWorkOrderList(@Param("popoUidList") List<String> popoUidList,
                                                                                     @Param("workOrderListFlag") Boolean workOrderListFlag,
                                                                                     @Param("wkStatus") String wkStatus,
                                                                                     @Param("userId") String userId) {
        if (StringUtils.isBlank(userId)) userId = SecurityUtil.getUserId();
        if (StringUtils.isBlank(wkStatus)) wkStatus = "new";
        if (workOrderListFlag == null) workOrderListFlag = true;
        return Result.success(sqfwWorkorderService.getPopoFriendNotCompleteWorkOrderList(popoUidList, workOrderListFlag, wkStatus, userId));
    }

    @At("/getWorkOrderListByIds")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据工单id获取工单列表")
    public Result<List<Sqfw_workorder>> getWorkOrderListByIds(@Param("wordOrderIdList") List<String> wordOrderIdList) {
        List<Sqfw_workorder> resultList = Lists.newArrayList();

        if (wordOrderIdList.size() == 0) return Result.success(resultList);

        resultList = sqfwWorkorderService.query(Cnd.where("id", "in", wordOrderIdList).and("delflag", "=", false));
        return Result.success(resultList);
    }
}
